package org.meetunexpectedly.controller.middleground;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.meetunexpectedly.authority.Authority;
import org.meetunexpectedly.entity.middleground.*;
import org.meetunexpectedly.entity.vo.BasePage;
import org.meetunexpectedly.entity.vo.Result;
import org.meetunexpectedly.service.middleground.RolePermissionService;
import org.meetunexpectedly.service.middleground.RoleService;
import org.meetunexpectedly.service.middleground.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 角色控制器
 * @Author: pupil
 * @Date: 2024/09/03 下午 5:15
 */
@RestController
@RequestMapping("/authorize/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RolePermissionService rolePermissionService;


    /**
     * 获取权限树形集合
     *
     * @return
     */
    @GetMapping("/treeList")
    @Authority("permission:treeList")
    public List<Tree> treeList() {
        List<Tree> tree = roleService.tree();
        return tree;
    }

    /**
     * 分配用户角色
     *
     * @param assignRoleVO 分配角色信息
     * @return
     */
    @PostMapping("/assignRole")
    @Authority("user:assignRole")
    public Result assignRole(@RequestBody AssignRoleVO assignRoleVO) {
        return roleService.assignRole(assignRoleVO);
    }

    /**
     * 获取用户角色
     *
     * @param uId 用户id
     * @return 角色ids
     */
    @GetMapping("/getUserRole/{uId}")
    @Authority("role:getUserRole")
    public List getUserRole(@PathVariable Long uId) {
        List<Long> roleIds = userRoleService.list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, uId).select(UserRole::getRoleId))
                .stream().map(UserRole::getRoleId).collect(Collectors.toList());
        return roleIds;
    }

    /**
     * 初始化角色
     *
     * @return
     */
    @GetMapping("/initRole")
    @Authority("role:initRole")
    public List<Map<String, Object>> initRole() {
        // 查出所有角色
        List<Map<String, Object>> list = roleService.list(null).stream()
                .map(role -> {
                    Map<String, Object> data = new HashMap<>();
                    data.put("value", role.getId());
                    data.put("title", role.getName());
                    return data;
                }).collect(Collectors.toList());

        return list;
    }

    /**
     * 查询角色 ———— 分页查询
     *
     * @param basePage 基础分页信息
     * @param name 角色名称
     * @return
     */
    @GetMapping("/list")
    @Authority("role:list")
    public Result list(BasePage basePage, @RequestParam(required = false) String name) {
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!ObjectUtils.isEmpty(name), Role::getName, name);
        IPage iPage = basePage.page();
        IPage<Role> page = roleService.page(iPage, wrapper);
        return Result.ok().data(page.getRecords()).count(page.getRecords().size());
    }

    /**
     * 添加角色
     *
     * @param role 角色
     * @return
     */
    @PostMapping
    @Authority("role:add")
    public Result addRole(@RequestBody Role role) {
        roleService.save(role);
        return Result.ok();
    }

    /**
     * 修改角色
     *
     * @param role 角色
     * @return
     */
    @PutMapping
    @Authority("role:update")
    private Result updateRole(@RequestBody Role role) {
        roleService.updateById(role);
        return Result.ok();
    }

    /**
     * 删除角色
     *
     * @param id 角色id
     * @return
     */
    @DeleteMapping("/{id}")
    @Authority("role:delete")
    private Result deleteRole(@PathVariable Long id) {
        if (!roleService.removeRole(id)) {
            return Result.error().message("删除失败");
        }
        return Result.ok().message("删除成功");
    }

    /**
     * 给角色分配权限
     * 给角色分配权限前先把该角色的权限都删了
     *
     * @param authorityVO 权限信息
     * @return
     */
    @PostMapping("/authority")
    @Authority("role:authority")
    public Result authority(@RequestBody AuthorityVO authorityVO) {
        if (!roleService.assignPermission(authorityVO)){
          return Result.error().message("分配权限失败");
        }
        return Result.ok().message("分配权限成功");
    }

    /**
     * 获取角色权限
     * @param id
     * @return
     */
    @GetMapping("/getPermission/{id}")
    @Authority("role:getPermission")
    public Integer[] getPermission(@PathVariable Integer id){
        Integer[] permissionIds = rolePermissionService.list(new LambdaQueryWrapper<RolePermission>().eq(RolePermission::getRoleId, id))
                .stream().map(RolePermission::getPermissionId).toArray(Integer[]::new);

        return permissionIds;
    }
}
